// 文件系统状态
let currentPath = '';
let files = [];
let pathHistory = []; // 用于存储路径历史
console.log('初始化文件系统，当前路径:', currentPath);

// 格式化日期函数，显示年-月-日 时:分
function formatDate(dateString) {
    if (!dateString) return '';
    try {
        const date = new Date(dateString);
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，不足两位补0
        const day = String(date.getDate()).padStart(2, '0'); // 不足两位补0
        const hours = String(date.getHours()).padStart(2, '0'); // 不足两位补0
        const minutes = String(date.getMinutes()).padStart(2, '0'); // 不足两位补0
        return `${year}-${month}-${day} ${hours}:${minutes}`;
    } catch (error) {
        console.error('日期格式化错误:', error);
        return dateString; // 如果格式化失败，返回原始字符串
    }
}

// DOM元素
const fileListElement = document.getElementById('fileList');
const createFolderBtn = document.getElementById('createFolderBtn');
const uploadFileBtn = document.getElementById('uploadFileBtn');
const fileInput = document.getElementById('fileInput');
const modal = document.getElementById('modal');
const modalBody = document.getElementById('modalBody');
const closeModal = document.getElementById('closeModal');
const typeModal = document.getElementById('typeModal');
const fileTypeSelect = document.getElementById('fileTypeSelect');
const confirmTypeBtn = document.getElementById('confirmTypeBtn');
const cancelTypeBtn = document.getElementById('cancelTypeBtn');
const backButton = document.createElement('button');
backButton.textContent = '↩ 返回上一层';
backButton.className = 'back-button';
backButton.style.display = 'none';
backButton.style.margin = '0 20px 10px 20px';

// 添加返回按钮到页面
const fileBrowserSection = document.querySelector('.file-browser');
if (fileBrowserSection) {
    const breadcrumb = fileBrowserSection.querySelector('.breadcrumb');
    fileBrowserSection.insertBefore(backButton, breadcrumb);
}

let selectedType = null;

// 初始化
document.addEventListener('DOMContentLoaded', () => {
    currentPath = '';
    loadFileList();
    createFolderBtn.addEventListener('click', showCreateFolderModal);
    fileInput.addEventListener('change', handleFileUpload);
    closeModal.addEventListener('click', () => {modal.style.display = 'none';console.log('Modal closed')});
    uploadFileBtn.addEventListener('click', () => {
        typeModal.style.display = 'flex';
    });
    confirmTypeBtn.addEventListener('click', () => {
        selectedType = fileTypeSelect.value;
        typeModal.style.display = 'none';
        fileInput.click();
    });
    cancelTypeBtn.addEventListener('click', () => {
        typeModal.style.display = 'none';
    });
    fileInput.addEventListener('change', handleFileUpload);
    backButton.addEventListener('click', goBack);
    //检查用户是否首次访问，如果是则显示欢迎信息（只显示一次）
    if (!localStorage.getItem('welcomeMessageShown')) {
        modalBody.innerHTML = "<p>项目仍在积极开发中，比较遗憾的是，由于量化像模型的准确率问题，\n题目生成模块无法较好的进行，后续将进行workflow的优化</p>\
        <p>语音助手的唤醒请查看设置中的唤醒词，如果使用远程桌面rdp，请在连接时设置计算机资源在本地录制。语音助手唤醒后，通过'开始聊天'指令可以和大模型进行语音对话。</p>\
        <p>相关类型的文件在桌面testdataset文件夹，请选择相应的资料类型进行上传，测试阶段不进行远端服务器同步。</p>"
        modal.style.display = "block";
        //标记欢迎信息已显示
        localStorage.setItem('welcomeMessageShown', 'true');
    }
});

function loadFileList() {
    console.log('开始加载文件列表，路径:', currentPath);
    fetch(`/api/files?path=${currentPath}`, {
        method: 'GET',
        headers: {
            'Content-Type': 'application/json',
        }
    })
    .then(response => {
        console.log('加载文件列表响应状态:', response.status);
        if (!response.ok) {
            // alert('加载文件列表失败：请确认已登录或检查网络连接。');
            throw new Error('未登录或其他错误');
        }
        return response.json();
    })
    .then(data => {
        console.log('加载文件列表成功，文件数量:', data.length);
        files = data;
        renderFileList();
    })
    .catch(error => {
        console.error('加载文件列表失败:', error);
        // 添加错误处理，确保UI更新
        files = [];
        renderFileList();
    });
}

function renderFileList() {
    fileListElement.innerHTML = '';

    // 添加列表标题行
    const headerRow = document.createElement('div');
    headerRow.className = 'file-header';
    headerRow.innerHTML = `
        <div class="file-column name-column">名称</div>
        <div class="file-column type-column">类型</div>
        <div class="file-column size-column">大小</div>
        <div class="file-column modified-column">修改日期</div>
        <div class="file-column actions-column">操作</div>
    `;
    fileListElement.appendChild(headerRow);

    // 过滤掉..文件夹，只显示实际文件和文件夹
    const filteredFiles = files.filter(file => file.name !== '..');

    filteredFiles.forEach(file => {
        const fileItem = document.createElement('div');
        fileItem.className = 'file-item';

        let fileIcon = '📁';
        let fileTypeText = '文件夹';
        
        if (!file.isDirectory) {
            fileTypeText = '文件';
            const ext = file.name.split('.').pop()?.toLowerCase() || '';
            const fileIcons = {
                'pdf': '📄', 'doc': '📝', 'docx': '📝', 'jpg': '🖼️', 'jpeg': '🖼️', 'png': '🖼️',
            };
            fileIcon = fileIcons[ext] || '📄';
        }

        fileItem.innerHTML = `
            <div class="file-column name-column">
                <span class="file-icon">${fileIcon}</span>
                <span class="file-name">${file.name}</span>
            </div>
            <div class="file-column type-column">${fileTypeText}</div>
            <div class="file-column size-column">${file.isDirectory ? '' : (file.size/1024/1024).toFixed(2)}${file.isDirectory ? '' : 'MB'}</div>
            <div class="file-column modified-column">${formatDate(file.modified)}</div>
            <div class="file-column actions-column">
                ${file.isDirectory ? 
                    `<button class="open-folder" data-path="${file.path}">打开</button>` : 
                    `<button class="view-file" data-path="${file.path}" data-name="${file.name}">查看</button>`}
                <button class="rename-file" data-path="${file.path}">重命名</button>
                <button class="delete-file" data-path="${file.path}">删除</button>
            </div>
        `;

        fileListElement.appendChild(fileItem);
    });

    document.querySelectorAll('.open-folder').forEach(btn => {
        btn.addEventListener('click', () => openFolder(btn.dataset.path));
    });

    // 绑定查看文件按钮事件
    document.querySelectorAll('.view-file').forEach(btn => {
        btn.addEventListener('click', () => {
            const path = btn.dataset.path;
            const fileName = btn.dataset.name;
            viewFile(path, fileName);
        });
    });

    document.querySelectorAll('.rename-file').forEach(btn => {
        btn.addEventListener('click', () => showRenameModal(btn.dataset.path));
    });

    document.querySelectorAll('.delete-file').forEach(btn => {
        btn.addEventListener('click', () => deleteFile(btn.dataset.path));
    });
}

function openFolder(path) {
    console.log('打开文件夹:', path, '当前路径:', currentPath);
    // 保存当前路径到历史记录
    if (currentPath !== '') {
        pathHistory.push(currentPath);
        console.log('保存路径到历史:', currentPath, '历史记录:', pathHistory);
    }
    
    currentPath = path;
    
    // 更新路径显示，显示文件夹名称而不是完整路径
    const pathElement = document.querySelector('.path');
    if (pathElement) {
        // 如果是根目录，使用用户名或默认文本
        if (path === '') {
            const token = getCookie('token');
            if (token) {
                const username = localStorage.getItem('username') || '用户';
                pathElement.textContent = username;
            } else {
                pathElement.textContent = '未登录';
            }
        } else {
            // 只显示当前文件夹名称
            const folderName = path.split('/').pop() || path;
            pathElement.textContent = folderName;
        }
    }
    
    // 显示或隐藏返回按钮
    backButton.style.display = path === '' ? 'none' : 'block';
    
    // 强制重新加载文件列表
    console.log('准备加载文件列表，当前路径:', currentPath);
    loadFileList();
}

// 查看文件内容函数
function viewFile(path, fileName) {
    console.log('查看文件:', fileName, '路径:', path);
    
    // 创建查看文件的模态框
    const fileViewModal = document.createElement('div');
    fileViewModal.className = 'modal';
    fileViewModal.style.display = 'block';
    fileViewModal.style.zIndex = '1001'; // 确保在其他模态框之上
    
    // 创建模态框内容
    const modalContent = document.createElement('div');
    modalContent.className = 'modal-content';
    modalContent.style.maxWidth = '80%';
    modalContent.style.maxHeight = '80vh';
    
    // 创建模态框头部
    const modalHeader = document.createElement('div');
    modalHeader.style.display = 'flex';
    modalHeader.style.justifyContent = 'space-between';
    modalHeader.style.alignItems = 'center';
    modalHeader.style.marginBottom = '10px';
    
    const modalTitle = document.createElement('h3');
    modalTitle.textContent = `查看文件: ${fileName}`;
    
    const closeButton = document.createElement('button');
    closeButton.textContent = '关闭';
    closeButton.addEventListener('click', () => {
        document.body.removeChild(fileViewModal);
    });
    
    modalHeader.appendChild(modalTitle);
    modalHeader.appendChild(closeButton);
    
    // 创建文件内容区域
    const fileContent = document.createElement('div');
    fileContent.className = 'file-content';
    fileContent.style.maxHeight = '60vh';
    fileContent.style.overflowY = 'auto';
    fileContent.style.padding = '10px';
    fileContent.style.backgroundColor = '#f9f9f9';
    fileContent.style.border = '1px solid #ddd';
    fileContent.style.borderRadius = '4px';
    fileContent.textContent = '加载文件内容中...';
    
    // 添加到模态框
    modalContent.appendChild(modalHeader);
    modalContent.appendChild(fileContent);
    fileViewModal.appendChild(modalContent);
    
    // 添加到文档
    document.body.appendChild(fileViewModal);
    
    // 获取文件内容
    fetch(`/api/files/view?path=${path}`, {
        method: 'GET',
        headers: {
            'Content-Type': 'application/json',
        }
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('加载文件内容失败');
        }
        return response.text();
    })
    .then(content => {
        // 简单的代码高亮（可选）
        const ext = fileName.split('.').pop()?.toLowerCase() || '';
        const isTextFile = ['txt', 'md', 'html', 'css', 'js', 'py', 'java', 'c', 'cpp', 'cs', 'php', 'sql', 'xml', 'json'].includes(ext);
        
        if (isTextFile) {
            // 文本文件，显示内容
            fileContent.textContent = content;
        } else {
            // 非文本文件，显示提示
            fileContent.textContent = `无法直接查看此文件类型(${ext})的内容。\n请下载文件后查看。`;
        }
    })
    .catch(error => {
        console.error('查看文件失败:', error);
        fileContent.textContent = `加载文件内容失败: ${error.message}`;
    });
    
    // 点击模态框外部关闭
    fileViewModal.addEventListener('click', (e) => {
        if (e.target === fileViewModal) {
            document.body.removeChild(fileViewModal);
        }
    });
}

// 返回上一层函数
function goBack() {
    console.log('返回上一层，路径历史:', pathHistory);
    if (pathHistory.length > 0) {
        const previousPath = pathHistory.pop();
        console.log('返回的路径:', previousPath);
        currentPath = previousPath;
        
        // 更新路径显示
        const pathElement = document.querySelector('.path');
        if (pathElement) {
            if (previousPath === '') {
                const token = getCookie('token');
                if (token) {
                    const username = localStorage.getItem('username') || '用户';
                    pathElement.textContent = username;
                } else {
                    pathElement.textContent = '未登录';
                }
            } else {
                const folderName = previousPath.split('/').pop() || previousPath;
                pathElement.textContent = folderName;
            }
        }
        
        // 显示或隐藏返回按钮
        backButton.style.display = previousPath === '' ? 'none' : 'block';
        
        // 强制重新加载文件列表
        console.log('准备加载文件列表，当前路径:', currentPath);
        loadFileList();
    } else {
        console.log('没有可返回的历史路径');
        // 如果没有历史记录，强制返回根目录
        currentPath = '';
        
        // 更新路径显示
        const pathElement = document.querySelector('.path');
        if (pathElement) {
            const token = getCookie('token');
            if (token) {
                const username = localStorage.getItem('username') || '用户';
                pathElement.textContent = username;
            } else {
                pathElement.textContent = '未登录';
            }
        }
        
        backButton.style.display = 'none';
        loadFileList();
    }
}

// 获取Cookie的辅助函数
function getCookie(name) {
    const cookies = document.cookie.split('; ');
    for (let cookie of cookies) {
        const [key, value] = cookie.split('=');
        if (key === name) return value;
    }
    return null;
}

function createFolder() {
    const folderName = document.getElementById('folderName').value;
    if (!folderName) return;

    fetch('/api/folder', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            
        },
        body: JSON.stringify({ name: folderName, path: currentPath })
    })
    .then(response => {
        if (response.ok) {
            loadFileList();
            modal.style.display = 'none';
        } else {
            response.json().then(err => alert(`创建失败: ${err.error}`));
        }
    })
    .catch(error => console.error('创建文件夹错误:', error));
}

function handleFileUpload(event) {
    const files = event.target.files;
    if (files.length === 0) return;

    const formData = new FormData();
    for (let i = 0; i < files.length; i++) {
        formData.append('files', files[i]);
    }
    const fileType = document.getElementById('fileTypeSelect').value;
    formData.append('path', currentPath);
    formData.append('file_type', fileType);

    // 显示加载动画
    document.getElementById('upload-loading').style.display = 'block';

    fetch('/api/upload', {
        method: 'POST',
        headers: {
            
        },
        body: formData
    })
    .then(response => {
        if (response.ok) {
            return response.json().then(data => {
                alert(`${data.message}: ${data.filenames.join(', ')}`);
                loadFileList();
            });
        } else {
            return response.json().then(err => {
                alert(`上传失败: ${err.error}`);
            });
        }
    })
    .catch(error => {
        console.error('上传错误:', error);
        alert('上传过程中发生错误。');
    })
    .finally(() => {
        // 无论成功与否，隐藏加载动画
        document.getElementById('upload-loading').style.display = 'none';
    });
}

function renameFile(filePath) {
    const newName = document.getElementById('newName').value;
    if (!newName) return;

    fetch('/api/rename', {
        method: 'PUT',
        headers: {
            'Content-Type': 'application/json',
            
        },
        body: JSON.stringify({ path: filePath, newName: newName })
    })
    .then(response => {
        if (response.ok) {
            loadFileList();
            modal.style.display = 'none';
        } else {
            response.json().then(err => alert(`重命名失败: ${err.error}`));
        }
    })
    .catch(error => console.error('重命名错误:', error));
}

function deleteFile(file_path) {
    if (!confirm('确定要删除这个文件吗？')) return;
    // 显示加载动画
    document.getElementById('upload-loading').style.display = 'block';
    fetch('/api/delete', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            
        },
        body: JSON.stringify({ path: file_path })
    })
    .then(response => {
        if (response.ok) {
            loadFileList();
        } else {
            response.json().then(err => alert(`删除失败: ${err.error}`));
        }
    })
    .catch(error => console.error('删除错误:', error))
    .finally(() => {
        // 无论成功与否，隐藏加载动画
        document.getElementById('upload-loading').style.display = 'none';
    });
}

function showRenameModal(file_path) {
    const file = files.find(f => f.path === file_path);
    const currentName = file ? file.name : '';

    modalBody.innerHTML = `
        <h2>重命名</h2>
        <div class="form-group">
            <label for="newName">新名称</label>
            <input type="text" id="newName" value="${currentName}">
        </div>
        <button id="renameConfirm">确认</button>
    `;

    modal.style.display = 'block';
    document.getElementById('renameConfirm').addEventListener('click', () => renameFile(file_path));
}

function showCreateFolderModal() {
    modalBody.innerHTML = `
        <h2>新建文件夹</h2>
        <div class="form-group">
            <label for="folderName">文件夹名称</label>
            <input type="text" id="folderName" placeholder="输入文件夹名称">
        </div>
        <button id="createFolderConfirm">创建</button>
    `;

    modal.style.display = 'block';

    document.getElementById('createFolderConfirm').addEventListener('click', createFolder);
}